/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.infrastructure.core.aspect.controller.children;

import cn.hallele.infrastructure.metadata.constant.MsgCodeConst;
import cn.hallele.infrastructure.metadata.io.Response;
import cn.hallele.ms.infrastructure.core.aspect.controller.BaseExceptionAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 基础异常处理
 *
 * @author anle5
 * @since 2024/9/15 0:30
 */
@Slf4j
@RestControllerAdvice
@Order(20)
public class BottomExceptionAspect extends BaseExceptionAspect {
    /**
     * 拦截所有 exception 的报错
     *
     * @param e {@link Exception}
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    public Response<?> exception(Exception e) {
        String msgCode = MsgCodeConst.FAILED;
        String msgDesc = i18n.getMessage(msgCode, new Object[]{}, getLocale());
        log.error("Find an Exception. MsgCode: {}, msgDesc: {}.", msgCode, msgDesc, e);
        return buildResponse(msgCode, msgDesc);
    }

    /**
     * 拦截所有 throwable 的报错
     *
     * @param e {@link Throwable}
     * @return 错误响应
     */
    @ExceptionHandler(Throwable.class)
    public Response<?> throwable(Throwable e) {
        String msgCode = MsgCodeConst.FAILED;
        String msgDesc = i18n.getMessage(msgCode, new Object[]{}, getLocale());
        log.error("Find an Throwable. MsgCode: {}, msgDesc: {}.", msgCode, msgDesc, e);
        return buildResponse(msgCode, msgDesc);
    }

    /**
     * 国际化
     *
     * @param i18n 国际化
     */
    public BottomExceptionAspect(MessageSource i18n) {
        super(i18n);
    }
}
